/*
 * @FileName: OrganizationService.java
 * 
 * @Author
 * 
 * @Description:
 * 
 * @Date 2016年1月7日 下午2:42:39
 * 
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.Reward;
import cn.hpclub.server.model.SalePromotion;
import cn.hpclub.server.model.ServiceReservation;

/**
 * Class description goes here
 *
 * @author
 */
public class SalePromotionService{

    private static final Logger        logger  = LoggerFactory.getLogger(SalePromotionService.class);
    public static SalePromotionService service = new SalePromotionService();

    public String queryMonthIncomeList(int userid, int num, int size){
        // userid = 6341027;
        try{
            Page<Record> page = SalePromotion.dao.query(userid, num, size);
            List<Record> list = page.getList();
            // Set<String> set = new HashSet<String>();
            // String temp;
            // for(Record sale : list){
            // temp = new
            // SimpleDateFormat("yyyy-MM").format(sale.getDate(SalePromotion.TIME));
            // temp = temp.replace("-", "年") + "月";
            // set.add(temp);
            // }
            // Object[] time = set.toArray();
            // Arrays.sort(time);
            JSONObject result = new JSONObject();
            JSONArray ja = new JSONArray();
            for(int i = 0; i < list.size(); i++){
                ja.put(list.get(i).getStr("fmttime"));
            }
            result.put(ClientApiConstant.Key.SALE_INDEX, num);
            result.put(ClientApiConstant.Key.SALE_SIZE, size);
            result.put(ClientApiConstant.Key.TOTAL_COUNT, page.getTotalRow());
            result.put(ClientApiConstant.Key.TOTAL_PAGE, page.getTotalPage());
            result.put(ClientApiConstant.Key.RESULT_CODE, ClientApiConstant.ResultCode.SUCCESS_CODE);
            result.put(ClientApiConstant.Key.MESSAGE, ClientApiConstant.Msg.SUCCESS);
            result.put(ClientApiConstant.Key.DATA, ja);
            return result.toString();
        }
        catch(Exception e){
            return new JSONObject().put(ClientApiConstant.Key.RESULT_CODE, ClientApiConstant.ResultCode.SUCCESS_CODE)
                    .put(ClientApiConstant.Key.MESSAGE, ClientApiConstant.Msg.MSG_EXCEPTION)
                    .put(ClientApiConstant.Key.DATA, "[]").toString();
        }
    }

    public String queryCurrentMonthIncome(int userid, String time, boolean isHistory){
        try{
            // userid = 6341027;

            JSONArray ja = new JSONArray();
            JSONObject temp = new JSONObject();
            HashMap<Integer, JSONObject> map = new HashMap<Integer, JSONObject>();
            Double totalCount = 0.00;
            Double totalAmount = 0.00;

            // 查询其他业务预估酬金
            List<SalePromotion> list = SalePromotion.dao.query(userid, time);
            for(SalePromotion sale : list){
                totalCount += 1;
                totalAmount += sale.getBigDecimal(SalePromotion.REWARD).doubleValue();
                if(map.containsKey(sale.getInt(SalePromotion.MODULEID))){
                    temp = map.get(sale.getInt(SalePromotion.MODULEID));
                    temp.put(ClientApiConstant.Key.SALE_COUNT, temp.getInt(ClientApiConstant.Key.SALE_COUNT) + 1);
                    temp.put(ClientApiConstant.Key.AMOUNT, temp.getDouble(ClientApiConstant.Key.AMOUNT)
                            + sale.getBigDecimal(SalePromotion.REWARD).doubleValue());
                    map.put(sale.getInt(SalePromotion.MODULEID), temp);
                } else{
                    temp = new JSONObject();
                    temp.put(ClientApiConstant.Key.SALE_COUNT, 1);
                    temp.put(ClientApiConstant.Key.AMOUNT, sale.getBigDecimal(SalePromotion.REWARD).doubleValue());
                    map.put(sale.getInt(SalePromotion.MODULEID), temp);
                    switch(sale.getInt(SalePromotion.MODULEID)){
                        case 1:
                            temp.put((ClientApiConstant.Key.SALE_NAME), Constant.ModuleName.JIAOFEI);
                            break;
                        case 2:
                            temp.put((ClientApiConstant.Key.SALE_NAME), Constant.ModuleName.KAIKA);
                            break;
                        case 3:
                            temp.put((ClientApiConstant.Key.SALE_NAME), Constant.ModuleName.XUANHAO);
                            break;
                        case 4:
                            temp.put((ClientApiConstant.Key.SALE_NAME), Constant.ModuleName.ZIFEI);
                            break;
                        case 5:
                            temp.put((ClientApiConstant.Key.SALE_NAME), Constant.ModuleName.BUDENGJI);
                            break;
                        case 6:
                            temp.put((ClientApiConstant.Key.SALE_NAME), Constant.ModuleName.YINGXIAO);
                            break;
                        case 7:
                            temp.put((ClientApiConstant.Key.SALE_NAME), Constant.ModuleName.KUANDAI);
                            break;
                        default:
                            temp.put((ClientApiConstant.Key.SALE_NAME), Constant.ModuleName.DEFAULT);
                            break;
                    }
                }
            }

            ja = new JSONArray();
            Iterator<JSONObject> iterator = map.values().iterator();
            while(iterator.hasNext()){
                temp = iterator.next();
                double amount = temp.getDouble(ClientApiConstant.Key.AMOUNT);
                temp.put(ClientApiConstant.Key.AMOUNT,
                         Double.parseDouble(new DecimalFormat("######0.00").format((isHistory) ? 0.00 : amount)));
                ja.put(temp);
            }

            // 查询宽带预估酬金
            List<ServiceReservation> kdList = ServiceReservation.dao.queryReward(userid, time);
            if(kdList != null && kdList.size() > 0){
                ServiceReservation sr = kdList.get(0);
                long saleCount = sr.getLong(ClientApiConstant.Key.SALE_COUNT);
                if(sr.getLong(ClientApiConstant.Key.SALE_COUNT) == null)
                    saleCount = 0;
                double amount = 0.00;
                if(sr.getBigDecimal(ClientApiConstant.Key.AMOUNT) != null)
                    amount = sr.getBigDecimal(ClientApiConstant.Key.AMOUNT).doubleValue();

                totalCount += saleCount;
                totalAmount += amount;

                temp = new JSONObject();
                temp.put((ClientApiConstant.Key.SALE_NAME), Constant.ModuleName.KUANDAI);
                temp.put(ClientApiConstant.Key.SALE_COUNT, saleCount);
                temp.put(ClientApiConstant.Key.AMOUNT,
                         Double.parseDouble(new DecimalFormat("######0.00").format((isHistory) ? 0.00 : amount)));

                ja.put(temp);
            }

            temp = new JSONObject();
            temp.put(ClientApiConstant.Key.INCOME_LIST, ja);
            temp.put(ClientApiConstant.Key.TOTAL_COUNT, totalCount);
            temp.put(ClientApiConstant.Key.TOTAL_AMOUNT,
                     Double.parseDouble(new DecimalFormat("######0.00").format((isHistory) ? 0.00 : totalAmount)));
            ja = new JSONArray().put(temp);
            temp = new JSONObject();
            temp.put(ClientApiConstant.Key.RESULT_CODE, ClientApiConstant.ResultCode.SUCCESS_CODE);
            temp.put(ClientApiConstant.Key.MESSAGE, ClientApiConstant.Msg.SUCCESS);
            temp.put(ClientApiConstant.Key.DATA, ja);

            return temp.toString();
        }
        catch(Exception e){
            return new JSONObject().put(ClientApiConstant.Key.RESULT_CODE, ClientApiConstant.ResultCode.SUCCESS_CODE)
                    .put(ClientApiConstant.Key.MESSAGE, ClientApiConstant.Msg.MSG_EXCEPTION)
                    .put(ClientApiConstant.Key.DATA, "[]").toString();
        }

    }

    /**
     * @param sale
     * @Title: getRechargeReward
     * @Description:充值缴费酬金计算
     * @return Double
     */
    public Double getRechargeReward(SalePromotion sale){
        Double rd = 0.00;
        List<Record> listReward = SalePromotion.dao
                .findReward(sale.getInt(SalePromotion.USERID), sale.getStr(SalePromotion.BUSINESS_CODE),
                            sale.getInt(SalePromotion.ORG_ID), sale.getInt(SalePromotion.MODULEID));

        if(listReward != null && listReward.size() > 0
                && Integer.parseInt(sale.getStr(SalePromotion.RETURN_CODE)) == 0){
            Record reward = listReward.get(0);
            Double temp = 0.00;
            Double sum = reward.getBigDecimal("sum").doubleValue();
            Double sumModule = reward.getBigDecimal("sumModule").doubleValue();
            Double clerk = 0.00;
            boolean tag_module = false;
            boolean tag_sum = false;
            if(reward.getLong("count") <= 0){
                temp = reward.getBigDecimal(Reward.FIRST_REWARD).doubleValue();
            } else{
                temp = reward.getBigDecimal(Reward.NORMAL_REWARD).doubleValue();
            }

            List<Record> listClerk = SalePromotion.dao.findClerkReward(sale.getInt(SalePromotion.MODULEID),
                                                                       sale.getInt(SalePromotion.ORG_ID));
            if(listClerk != null && listClerk.size() >= 1){
                for(Record r : listClerk){
                    if(r.getInt("moduleid") == sale.getInt(SalePromotion.MODULEID)){
                        clerk = r.getBigDecimal("single_cap").doubleValue() <= 0 ? Double.MAX_VALUE
                                : r.getBigDecimal("single_cap").doubleValue();

                        sumModule = sumModule >= clerk ? 0.00 : clerk - sumModule;
                        tag_module = true;
                        // sumModule = sumModule >=
                        // r.getBigDecimal("single_cap").doubleValue() ? 0.00
                        // : r.getBigDecimal("single_cap").doubleValue() -
                        // sumModule;
                    } else{
                        clerk = r.getBigDecimal("single_cap").doubleValue() <= 0 ? Double.MAX_VALUE
                                : r.getBigDecimal("single_cap").doubleValue();

                        sum = sum >= clerk ? 0.00 : clerk - sum;
                        tag_sum = true;
                        // sum = sum >=
                        // r.getBigDecimal("single_cap").doubleValue() ? 0.00
                        // : r.getBigDecimal("single_cap").doubleValue() - sum;
                    }
                }
            }

            if(!tag_module){
                sumModule = Double.MAX_VALUE;
            }
            if(!tag_sum){
                sum = Double.MAX_VALUE;
            }

            rd = min(temp, sum, sumModule);
        }
        return rd;
    }

    /**
     * @Title: min
     * @Description:TODO
     * @param temp
     * @param sum
     * @param sumModule
     * @return Double
     */
    private double min(double reward, double sum, double sumModule){
        double min = reward;
        if(sum < min){
            min = sum;
        }
        if(sumModule < min){
            min = sumModule;
        }
        return Double.parseDouble(new DecimalFormat("######0.00").format(min));
    }
}
